import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

class Register extends StatelessWidget {
  final String uniqueId;
  //初始化函数
  Register({Key key, @required this.uniqueId}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        automaticallyImplyLeading: false, // 去除返回按钮
        title: Text('注册'),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(
            padding: EdgeInsets.all(16.0),
            child: KeyboardAvoider(
              autoScroll: true,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RegisterForm(uniqueId: this.uniqueId),
                ],
              ),
            )),
      ),
    );
  }
}

class RegisterForm extends StatefulWidget {
  final String uniqueId;
  //初始化函数
  RegisterForm({Key key, @required this.uniqueId}) : super(key: key);
  @override
  RegisterFormState createState() => RegisterFormState(uniqueId: this.uniqueId);
}

class RegisterFormState extends State<RegisterForm> {
  String codeImgUrl;
  String uniqueId;
  //初始化函数
  RegisterFormState({Key key, @required this.uniqueId});
  final registerFormKey = GlobalKey<FormState>();
  String username, nickname, password, repassword, email, code;
  bool autovalidate = false;
  void submitRegisterForm() {
    if (registerFormKey.currentState.validate()) {
      registerFormKey.currentState.save();
      this.fetchPosts(username, nickname, password, repassword, email, code);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateRequired(value) {
    if (value.isEmpty) {
      return '请正确填写此字段！';
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    print('AA=uniqueId');
    print(uniqueId);
    if (codeImgUrl == null || codeImgUrl == '') {
      codeImgUrl = 'https://me.yuanqiao.pw/api/me/captcha.php?deviceId=' +
          (uniqueId != null ? uniqueId : '') +
          '&random=' +
          Random().nextInt(100).toString();
    }
    print(codeImgUrl);
    return Form(
      key: registerFormKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              labelText: '用户名',
              helperText: '',
            ),
            onSaved: (value) {
              username = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            decoration: InputDecoration(
              labelText: '昵称',
              helperText: '',
            ),
            onSaved: (value) {
              nickname = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '密码',
              helperText: '',
            ),
            onSaved: (value) {
              password = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '重复密码',
              helperText: '',
            ),
            onSaved: (value) {
              repassword = value;
            },
            validator: validateRequired,
          ),
          TextFormField(
            keyboardType: TextInputType.emailAddress,
            decoration: InputDecoration(
              labelText: '邮箱',
              helperText: '',
            ),
            onSaved: (value) {
              email = value;
            },
            validator: validateRequired,
          ),
          // Container(
          //   child: Image.network(codeImgUrl),
          // ),
          TextFormField(
            decoration: InputDecoration(
                labelText: '图形验证码',
                helperText: '',
                suffixIcon: Image.network(codeImgUrl)),
            onSaved: (value) {
              code = value;
            },
            validator: validateRequired,
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
            width: double.infinity,
            child: ElevatedButton(
              // color: Theme.of(context).accentColor,
              child: Text('注册', style: TextStyle(color: Colors.white)),
              onPressed: submitRegisterForm,
            ),
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
              width: double.infinity,
              child: Row(
                children: <Widget>[
                  Text('已有账号，去'),
                  TextButton(
                    style: ButtonStyle(
                        // foregroundColor: Theme.of(context).accentColor, //字体颜色
                        elevation: MaterialStateProperty.all(0)),
                    child: Text('登录',
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.w500)),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              )),
        ],
      ),
    );
  }

  Future fetchPosts(
      $username, $nickname, $password, $repassword, $email, $code) async {
    var dataBody = jsonEncode({
      'username': $username,
      'nickname': $nickname,
      'password': $password,
      'repassword': $repassword,
      'email': $email,
      'code': $code,
      'deviceId': uniqueId
    });
    final response = await http
        .post('https://me.yuanqiao.pw/api/me/register.php', body: dataBody);
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      var state = responseBody['state'];
      if (state == '1') {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        // prefs.setString(key, value)
        // prefs.setBool(key, value)
        // prefs.setDouble(key, value)
        // prefs.setInt(key, value)
        // prefs.setStringList(key, value)
        final setTokenResult =
            await prefs.setString('username', responseBody['data']['username']);
        if (setTokenResult) {
          Fluttertoast.showToast(
              msg: '注册成功',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
          Navigator.of(context).pushNamedAndRemoveUntil(
            '/login',
            (route) => route == null,
          );
        } else {
          Fluttertoast.showToast(
              msg: '保存登录token失败',
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
        }
      } else {
        if (mounted) {
          setState(() {
            codeImgUrl = 'https://me.yuanqiao.pw/api/me/captcha.php?deviceId=' +
                (uniqueId != null ? uniqueId : '') +
                '&random=' +
                Random().nextInt(100).toString();
          });
        }
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
